package com.dome.auth.utils;

import com.dome.redis.utils.JedisUtils;
import com.dome.user.entity.dto.UserLoginDTO;
import com.dome.auth.UserContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户工具类
 * 
 * @author vanlin
 *
 */
public final class UserUtil {
	private final static Logger logger = LoggerFactory.getLogger(UserUtil.class);
	public static final String KEY_USERLOGINENTITY = "KEY_USERLOGIN";

	/**
	 *
	 * @return
	 */
	public static final UserLoginDTO getPrincipal() {
		String account = account();
		if(StringUtils.isNotEmpty(account)) {
			//从上下文取
			Object obj = UserContextHolder.getInstance().get(UserUtil.KEY_USERLOGINENTITY);
			UserLoginDTO userLogin = null;
			if(obj!=null) {
				userLogin = (UserLoginDTO) obj;
			}
			if(userLogin==null) {
				//从redis取
				userLogin = JedisUtils.getObject(account);
				if(userLogin!=null) {
					UserContextHolder.getInstance().set(UserUtil.KEY_USERLOGINENTITY,userLogin);
				}
			}
			return userLogin;
		}
		return null;
	}

	private static String account() {
		String token = UserContextHolder.getInstance().getToken();
		if(token!=null) {
			String account = JwtUtils.loginRedisKey(token);
			return account;
		}
		return null;
	}


	/**
	 * 获取用户邮箱
	 *
	 * @return
	 */
	public static final String getEmail() {
		final UserLoginDTO user = getPrincipal();
		if(user!=null&&StringUtils.isNotBlank(user.getEmail())) {
			return user.getEmail();
		}
		return null;
	}


	/**
	 * 获取用户邮箱
	 *
	 * @return
	 */
	public static final String getUserName() {
		final UserLoginDTO user = getPrincipal();
		if(user!=null&&StringUtils.isNotBlank(user.getEmail())) {
			return user.getUserName();
		}
		return null;
	}


	/**
	 * 获取用户ID
	 *
	 * @return
	 */
	public static final Long getId() {
		final UserLoginDTO user = getPrincipal();

		if(user!=null&&user.getId()!=null) {
			return user.getId();
		}
		return null;
	}


	/**
	 * 获取用户所有信息
	 *
	 * @return
	 */
	public static final UserLoginDTO getUserLogin() {
		final UserLoginDTO user = getPrincipal();
		return user;
	}


}
